package com.cloud.bssp.nio.aio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @description： TODO
 * @author：weirx
 * @date：2021/11/5 15:02
 * @version：3.0
 */
public class TestAio {

    public static void main(String[] args) throws IOException {
        try {
            AsynchronousFileChannel s = AsynchronousFileChannel.open(
                            Paths.get("C:\\Users\\P50\\Desktop\\text.txt"), StandardOpenOption.READ);
            ByteBuffer buffer = ByteBuffer.allocate(10);
            System.out.println("begin...");
            s.read(buffer, 0, null, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    System.out.println("read completed..." + result);
                    buffer.flip();
                    System.out.println(Thread.currentThread().getName() + "，内容是：" + print(buffer));
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    System.out.println("ead failed...");
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("do other things...");
        System.in.read();
    }

    static String print(ByteBuffer b) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < b.limit(); i++) {
            stringBuilder.append((char) b.get(i));
        }
        return stringBuilder.toString();
    }
}
